"""
Views that return JSON pages.
"""

from django.contrib.auth.decorators import login_required
from django.utils import simplejson as json
from django.http import HttpResponse
from django.shortcuts import get_list_or_404

from track.models import Itinerary
from track.models import Checkpoint
from track.models import Vehicle

@login_required
def itineraries(request):
  """Obtain list of itineraries"""
  response = HttpResponse(mimetype='application/json')
  
  itineraries = dict(
    (itinerary.id, {
      'name':        itinerary.name,
      'slug':        itinerary.slug,
      'description': itinerary.description,
      'is_mine':     itinerary.user == request.user,
      'checkpoints': dict(
        (checkpoint.order, (checkpoint.x, checkpoint.y)) for checkpoint in itinerary.checkpoint_set.all()
      )
    }) for itinerary in Itinerary.objects.all().select_related())
  
  response.write(json.dumps(itineraries))
  
  return response

@login_required
def checkpoints(request, itinerary):
  """Obtain an itinerary's list of checkpoints"""
  response = HttpResponse(mimetype='application/json')
  
  checkpoints = get_list_or_404(Checkpoint, itinerary__slug=itinerary)
  
  checkpoints = [(checkpoint.x, checkpoint.y) for checkpoint in checkpoints]
  
  response.write(json.dumps(checkpoints))
  
  return response

@login_required
def vehicles(request):
  """Obtain list of vehicles"""
  response = HttpResponse(mimetype='application/json')
  
  vehicles = dict(
    (vehicle.id, {
    'name':        vehicle.name,
    'slug':        vehicle.slug,
    'description': vehicle.description,
    'itinerary':   vehicle.checkpoint.itinerary.id if vehicle.checkpoint else None,
    'is_mine':     vehicle.user == request.user
      }) for vehicle in Vehicle.objects.all())
  
  response.write(json.dumps(vehicles))
  
  return response

@login_required
def positions(request):
  """Obtain list of positions"""
  response = HttpResponse(mimetype='application/json')
  
  positions = dict(
    (vehicle.id, (vehicle.x, vehicle.y, vehicle.checkpoint.id if vehicle.checkpoint else None, vehicle.advancement))
      for vehicle in Vehicle.objects.all())
  
  response.write(json.dumps(positions))
  
  return response
